package fatboy.communication;

import java.io.Serializable;

public class PortNumber implements Serializable{
	/**
	 * stores the port number for an object ID and for a thread
	 */
	private static final long serialVersionUID = 1L;
	private static final int MAX_PORT_NUMBER = 65000;
	private static final int MIN_PORT_NUMBER = 0;
	private static final int DEFAULT_PORT = 4444;
	private static int portNumber = DEFAULT_PORT;
	private int port;
	/**
	 * constructor taking in the port number
	 * @param port port number to be saved
	 * @throws IllegalARgument exception if the port > 65000 or < 0
	 */
	public PortNumber(int port){
		if(!validPort(port)){
			throw new IllegalArgumentException("invalid port number");
		}
		this.port = port; 
	}
	/**
	 * Constructor using current threads PortNumber
	 */
	public PortNumber(){
		
		this.port = portNumber; 
	}
	/**
	 * returns stored Port Number
	 * @return Port Number
	 */
	public int getPort(){
		return port;
	}
	/**
	 *  returns the current threads PortNumber
	 * @return current threads PortNumber
	 */
	public static synchronized PortNumber getRuntimePort(){
		return new PortNumber(portNumber);
	}
	/**
	 *  Sets the current Threads PortNumber
	 * @param port number to be set
	 * @throws IllegalARgument exception if the port > 65000 or < 0 
	 */
	public static synchronized void setRuntimePort(int port){
		if(!validPort(port)){
			throw new IllegalArgumentException("invalid port number");	
		}
		portNumber = port;
	}
	/**
	 *  determines if a port is valid
	 * @param port2 port to be tested
	 * @return true or false depending on if it is valid port number
	 */
	private static boolean validPort(int port2) {
		return port2 <= MAX_PORT_NUMBER && port2 >= MIN_PORT_NUMBER;
	}
	public boolean equals(Object o){
		if(o instanceof PortNumber){
			return port == ((PortNumber)o).port;
		}
		return false;
	}
	public int hashCode(){
		return port;
	}
	public String toString(){
		return ""+port;
	}
}
